package com.nowcoder.community.contorller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.nowcoder.community.annotation.LoginReguired;
import com.nowcoder.community.dao.elasticsearch.DiscussPostRepository;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private DiscussPostRepository discussPostRepository;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Autowired
    private OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    //上传到OSS
    @LoginReguired
    @GetMapping("/setting")
    public String getSettingPage(Model model) {
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        //String callbackUrl = "http://88.88.88.88:8888";
        String dir = "header/"; // 用户上传文件时指定的前缀。

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);//+"/"+CommunityUtil.generateUUID()
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            respMap.put("key", CommunityUtil.generateUUID());
            // respMap.put("expire", formatISO8601Date(expiration));

            model.addAttribute("respMap", respMap);
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return "/site/setting";
    }

    //oss获取
    @ResponseBody
    @PostMapping("/header/url")
    public String updateHeaderUrl(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return CommunityUtil.getJSONString(1, "文件名不能为空");
        }

        String host = "https://" + bucket + "." + endpoint;
        String url = host + "/header/" + fileName + ".png";
        userService.updateHeader(hostHolder.getUser().getId(), url);

        return CommunityUtil.getJSONString(0);
    }

    //废弃 上传到本地
    //更新头像
    @LoginReguired
    @PostMapping("/upload")
    public String uploadHeader(@RequestParam("headerImage") MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "未选择图片");
            return "/site/setting";
        }

        //获取图片名
        String filename = headerImage.getOriginalFilename();
        //获取图片后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }

        //生成随机文件名
        filename = CommunityUtil.generateUUID() + suffix;
        //确定文件存放路径
        File dest = new File(uploadPath + "/" + filename);
        try {
            //存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            //上传失败
            System.out.println("upload error");
            throw new RuntimeException("上传文件失败，服务器异常 : ", e);
        }

        //更新当前用户头像路径（web路径
        //http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    //废弃 本地获取
    //获取头像
    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //服务器存放的路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            System.out.println("error: " + e.getMessage());
        }
    }

    //个人主页
    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }

        //用户
        model.addAttribute("user", user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        //是否以关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "site/profile";
    }

    //修改密码
    @PostMapping("/repassword")
    @ResponseBody
    public String rePassword(@RequestParam("password") String password, @RequestParam("repassword") String repassword,
                             @RequestParam("cpassword") String cpassword) {
        User user = hostHolder.getUser();

        if (user == null) {
            return CommunityUtil.getJSONString(0, "未知用户");
        }
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            return CommunityUtil.getJSONString(0, "请输入正确的原密码");
        }
        if (!repassword.equals(cpassword)) {
            return CommunityUtil.getJSONString(0, "确认密码与新密码不相同");
        }
        if (password.equals(CommunityUtil.md5(repassword + user.getSalt())) || password.equals(CommunityUtil.md5(cpassword + user.getSalt()))) {
            return CommunityUtil.getJSONString(0, "旧密码与新密码不能相同");
        }

        userService.updatePassword(user.getId(), CommunityUtil.md5(repassword + user.getSalt()));
        return CommunityUtil.getJSONString(0, "修改成功");
    }

    //我的帖子
    @GetMapping("/mypost/{userId}")
    public String myPost(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }

        Sort sort = Sort.by("createTime").descending();
        org.springframework.data.domain.Page<DiscussPost> posts =
                discussPostRepository.findDiscussPostByUserId(user.getId(), PageRequest.of(page.getCurrent() - 1, page.getLimit(), sort));

        page.setRows((int) posts.getTotalElements());

        List<Map<String, Object>> discussPosts = new ArrayList<>();
        posts.forEach(post -> {
            Map<String, Object> map = new HashMap<>();
            map.put("post", post);
            map.put("like", likeService.findEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, post.getId()));
            discussPosts.add(map);
        });

        //用户
        model.addAttribute("user", user);
        model.addAttribute("postCount", posts.getTotalElements());
        model.addAttribute("posts", discussPosts);

        return "/site/my-post";
    }

    //我的回复
    @GetMapping("/myreply/{userId}")
    public String myReplt(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }

        int count = commentService.findCountByUserId(user.getId());
        page.setRows(count);

        model.addAttribute("user", user);
        model.addAttribute("commentCount", count);
        List<Comment> comments = commentService.findCommentByUserId(user.getId(), page.getoffset(), page.getLimit());
        model.addAttribute("comments", comments);

        return "/site/my-reply";
    }
}
